<template>
  <el-tooltip placement="top" effect="customized" v-model:visible="visible">
    <template #content>
      <span>{{ t('component.table.settingColumn') }}</span>
    </template>
    <div>
      <el-popover placement="left-start" trigger="click" :width="320" @show="handleVisibleChange">
        <template #reference>
          <el-button class="svg-Btn" text @mouseenter="visible = true" @click="
          visible = false;" @mouseleave="visible = false">
            <template #icon>
              <SvgIcon icon-class="column-settings" :size="20"></SvgIcon>
            </template>
          </el-button>
        </template>
        <div>
          <div class="check-group-inline">
            <el-checkbox label="列展示" @change="onCheckAllChange" :checked="checkAll" />
            <el-checkbox label="序列号" :checked="checkIndex" @change="handleIndexCheckChange" />
            <el-checkbox label="勾选列" :checked="checkSelect" @change="handleSelectCheckChange" />
            <el-button size="small" text style="margin-left: 20px;font-size: 14px;" class="restart" @click="reset">重置
            </el-button>
          </div>
          <el-divider class="m10" />
          <el-scrollbar height="300px">
            <el-checkbox-group ref="columnListRef" v-model="checkedList" class="optionGroup" @change="onChange">
              <div :class="`${prefixCls}__check-item`" v-for="item in plainOptions" :key="item.value">
                <SvgIcon icon-class="drag-out" class="table-column-drag-icon"></SvgIcon>
                <el-checkbox :label="item.value">{{ item.label }}</el-checkbox>
                <div class="table-colum__fixed-right">
                  <el-tooltip placement="top" effect="customized">
                    <template #content>
                      <span>{{ t('component.table.settingFixedLeft') }}</span>
                    </template>
                    <el-button text>
                      <template #icon>
                        <SvgIcon icon-class="fixed-left" class="table-column__fixed-left" :size="20"></SvgIcon>
                      </template>
                    </el-button>

                  </el-tooltip>
                  <el-divider direction="vertical" />
                  <el-tooltip placement="top" effect="customized">
                    <template #content>
                      <span>{{ t('component.table.settingFixedRight') }}</span>
                    </template>
                    <el-button text>
                      <template #icon>
                        <SvgIcon icon-class="fixed-right" class="table-column__fixed-right" :size="20"></SvgIcon>
                      </template>
                    </el-button>
                  </el-tooltip>
                </div>
              </div>

            </el-checkbox-group>
          </el-scrollbar>
        </div>
      </el-popover>
    </div>
  </el-tooltip>
</template>

<script lang="ts" setup>
import { useDesign } from '@/hooks/web/useDesign';
import { useI18n } from '@/hooks/web/useI18n'
import { isNullAndUnDef } from '@/utils/is';
import { cloneDeep, omit } from 'lodash';
import { computed, nextTick, reactive, ref, toRefs, unref, watchEffect } from 'vue'
import { useTableContext } from '../../hooks/useTableContext'
import { BasicColumn, ColumnChangeParam } from '../../types/table';
import { ComponentRef } from '/#/index';
import { Recordable } from '/#/global';

import Sortablejs from 'sortablejs';
import type Sortable from 'sortablejs';


const emit = defineEmits<{
  (e: 'columns-change', data: ColumnChangeParam[]): void
}>()

const visible = ref(false)
const { t } = useI18n()
const table = useTableContext()


const columnListRef = ref<ComponentRef>(null);

const { prefixCls } = useDesign('basic-column-setting');


interface Options {
  label: string;
  value: string;
  fixed?: boolean | string | undefined;
}

interface State {
  checkAll: boolean;
  isInit?: boolean;
  //选择的列
  checkedList: string[];
  defaultCheckList: string[];
}

const plainOptions = ref<Options[] | any>([]);
const plainSortOptions = ref<Options[]>([]);
const cachePlainOptions = ref<Options[]>([]);


const state = reactive<State>({
  checkAll: true,
  checkedList: [],
  defaultCheckList: [],
});


const { checkAll, checkedList, defaultCheckList } = toRefs(state)
const checkIndex = ref(false);
const checkSelect = ref(false);


const getValues = computed(() => {
  return unref(table?.getBindValues) || {};
});



watchEffect(() => {
  const columns = table.getColumns().filter(item => item.type !== 'index' && item.type !== 'ACTION');
  if (columns.length && !state.isInit) {
    init()
  }
})

watchEffect(() => {
  const values = unref(getValues);
  checkIndex.value = !!values.showIndexColumn;
  checkSelect.value = !!values.rowSelection;

})

function getColumns() {
  const ret: Options[] = [];
  table.getColumns({ ignoreIndex: true, ignoreAction: true }).forEach(item => {
    ret.push({
      label: (item.label as string) || (item.customTitle as string),
      value: (item.id || item.label) as string,
      ...item
    })
  })
  return ret
}

function init() {
  const columns = getColumns();

  const checkList = table
    .getColumns({ ignoreAction: true })
    .map(item => {
      if (item.defaultHidden) {
        return ''
      }
      return item.id || item.label
    })
    .filter(Boolean) as string[]

  if (!plainOptions.value.length) {
    plainOptions.value = columns;
    plainSortOptions.value = columns;
    cachePlainOptions.value = columns;
    state.defaultCheckList = checkList;
  } else {
    unref(plainOptions).forEach((item: BasicColumn<Recordable>) => {
      const findItem = columns.find((col: BasicColumn<Recordable>) => col.id === item.id);
      if (findItem) {
        item.fixed = findItem.fixed
      }
    })
  }

  state.isInit = true
  state.checkedList = checkList
}
let inited = false;

let sortable: Sortable;
let sortableOrder: string[] = [];

function handleVisibleChange() {
  if (inited) return;
  nextTick(() => {
    const columnListEl = unref(columnListRef);
    if (!columnListEl) return;
    const el = columnListEl.$el as any;
    if (!el) return;
    // Drag and drop sort
    sortable = Sortablejs.create(unref(el), {
      animation: 500,
      delay: 400,
      delayOnTouchOnly: true,
      handle: '.table-column-drag-icon ',
      onEnd: (evt) => {
        const { oldIndex, newIndex } = evt;
        if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || oldIndex === newIndex) {
          return;
        }
        // Sort column
        const columns = cloneDeep(plainSortOptions.value);

        if (oldIndex > newIndex) {
          columns.splice(newIndex, 0, columns[oldIndex]);
          columns.splice(oldIndex + 1, 1);
        } else {
          columns.splice(newIndex + 1, 0, columns[oldIndex]);
          columns.splice(oldIndex, 1);
        }

        plainSortOptions.value = columns;
        setColumns(columns);
      },
    });
    // 记录原始order 序列
    sortableOrder = sortable.toArray();
    inited = true;
  })




}

function setColumns(columns: BasicColumn<Recordable>[] | string[]) {
  table.setColumns(columns);
  const data: ColumnChangeParam[] =
    unref(plainSortOptions).map(col => {
      const visible =
        columns.findIndex(
          (c: BasicColumn<Recordable> | string) =>
            c === col.label || (typeof c !== 'string' && c.id === col.value),
        ) !== -1;
      return { id: col.label, fixed: col.fixed, visible };

    }
    );

  emit('columns-change', data);
}

const onCheckAllChange = (value: string | number | boolean): any => {
  const checkList = plainOptions.value.map((item: any) => item.value);
  if (value) {
    state.checkedList = checkList;
    setColumns(checkList);
  } else {
    state.checkedList = [];
    setColumns([]);
  }

  return value
}

// reset columns
function reset() {
  state.checkedList = [...state.defaultCheckList];
  state.checkAll = true;
  plainOptions.value = unref(cachePlainOptions);
  plainSortOptions.value = unref(cachePlainOptions);
  setColumns(table.getCacheColumns());
  sortable.sort(sortableOrder);
}

// Trigger when check/uncheck a column
function onChange(checkedList: string[]) {
  const len = plainSortOptions.value.length;
  state.checkAll = checkedList.length === len;
  const sortList = unref(plainSortOptions).map((item) => item.value);
  checkedList.sort((prev, next) => {
    return sortList.indexOf(prev) - sortList.indexOf(next);
  });
  setColumns(checkedList);
}


// Control whether the serial number column is displayed
function handleIndexCheckChange(checked: string | number | boolean) {
  table.setProps({
    showIndexColumn: checked,
  });
}
const defaultRowSelection = omit(table.getRowSelection(), 'selectedRowKeys');

// Control whether the check box is displayed
function handleSelectCheckChange(checked: string | number | boolean) {
  table.setProps({
    rowSelection: checked ? defaultRowSelection : undefined,
  });
}
</script>

<style lang="scss">
.restart.el-button--text {
  font-size: 16px;

}

.check-group-inline {
  display: inline-flex;
  align-items: center;
}

.optionGroup {
  display: block;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.el-divider.m10 {
  margin: 10px 0;
}

.table-column-drag-icon {
  cursor: move;
  margin: 0 5px;
}

.gm-basic-column-setting__check-item {
  display: inline-flex;
  align-items: center;
  width: 100%;

  .el-checkbox {
    margin-left: 10px;
    min-width: 100px;
  }

  .table-colum__fixed-right {
    float: right;
    width: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .el-divider {
      height: 16px;
    }
  }
}
</style>